package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    ReportMapper reportMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    WorkspaceService workspaceService;

    /**
     * 销售额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        //日期列
        List<LocalDate> dates = new ArrayList<>();

        while(!begin.equals(end.plusDays(1))){
            dates.add(begin);
            begin = begin.plusDays(1);
        }

        //销售额列
        List<Double> turnovers = new ArrayList<>();



        for (LocalDate date : dates) {

            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);


            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = reportMapper.turnoverStatistics(map);
            turnover = turnover == null ? 0.0:turnover;
            turnovers.add(turnover);
        }



        TurnoverReportVO reportVO = TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dates,","))
                .turnoverList(StringUtils.join(turnovers,","))
                .build();

        return reportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistic(LocalDate begin, LocalDate end) {

        //日期列
        List<LocalDate> dates = new ArrayList<>();

        LocalDate begin1 = begin;
        while(!begin1.equals(end.plusDays(1))){
            dates.add(begin1);
            begin1 = begin1.plusDays(1);
        }

        //总用户列
        List<Integer> users = new ArrayList<>();

        LocalDate basebegin = LocalDate.of(2024,5,1);

        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(basebegin,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            Integer count = reportMapper.userStatistics(beginTime,endTime);
            count = count == null?0:count;

            users.add(count);
        }

        //新增用户量统计
        List<Integer> newUsers = new ArrayList<>();

        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            Integer count = reportMapper.userStatistics(beginTime,endTime);
            count = count == null?0:count;

            newUsers.add(count);
        }

        UserReportVO reportVO = UserReportVO
                .builder()
                .dateList(StringUtils.join(dates,","))
                .totalUserList(StringUtils.join(users,","))
                .newUserList(StringUtils.join(newUsers,","))
                .build();

        return reportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        LocalDate begin1 = begin;

        //日期列
        List<LocalDate> dates = new ArrayList<>();

        while(!begin.equals(end.plusDays(1))){
            dates.add(begin);
            begin = begin.plusDays(1);
        }

        Map map = new HashMap();

        //订单总数
        map.put("begin",LocalDateTime.of(begin1,LocalTime.MIN));
        map.put("end",LocalDateTime.of(end,LocalTime.MAX));
        map.put("status",null);
        Integer totalCount = reportMapper.ordersStatistics(map);

        //有效订单总数
        map.put("begin",LocalDateTime.of(begin1,LocalTime.MIN));
        map.put("end",LocalDateTime.of(end,LocalTime.MAX));
        map.put("status",Orders.COMPLETED);
        Integer validCount = reportMapper.ordersStatistics(map);

        //订单完成率
        double orderCompletionRate = (double) validCount/totalCount;

        //每日订单总数
        List<Integer> orderCountList = new ArrayList<>();

        for (LocalDate date : dates) {
            map.put("begin",LocalDateTime.of(date,LocalTime.MIN));
            map.put("end",LocalDateTime.of(date,LocalTime.MAX));
            map.put("status",null);
            Integer count = reportMapper.ordersStatistics(map);
            orderCountList.add(count);
        }

        //每日有效订单数
        List<Integer> validOrderCount = new ArrayList<>();

        for (LocalDate date : dates) {
            map.put("begin",LocalDateTime.of(date,LocalTime.MIN));
            map.put("end",LocalDateTime.of(date,LocalTime.MAX));
            map.put("status",Orders.COMPLETED);
            Integer count = reportMapper.ordersStatistics(map);
            validOrderCount.add(count);
        }

        OrderReportVO reportVO = OrderReportVO
                .builder()
                .dateList(StringUtils.join(dates,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCount,","))
                .totalOrderCount(totalCount)
                .validOrderCount(validCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return reportVO;
    }

    /**
     * 销量top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO topStatistics(LocalDate begin, LocalDate end) {

        List<Map<String,Object>> topList =new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        topList = reportMapper.topStatistics(beginTime,endTime);

        System.out.println(topList);

        List<String> nameList = new ArrayList<>();
        List<BigDecimal> numberList = new ArrayList<>();

        for (Map<String, Object> map : topList) {
            nameList.add((String) map.get("name"));
            numberList.add( (BigDecimal) map.get("count"));
        }

        SalesTop10ReportVO reportVO = SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();

        return reportVO;
    }

    /**
     * 导出excel文件
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {

        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */

        LocalDate begin = LocalDate.now().plusMonths(-1);
        LocalDate end = LocalDate.now();
        LocalDate begin1 = begin;

        LocalDateTime beginTime = LocalDateTime.of(LocalDate.now().plusMonths(-1),LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now(),LocalTime.MAX);

        //获取概览数据
        BusinessDataVO totalBusinessData = workspaceService.getBusinessData(beginTime, endTime);


        //获取最近一个月的日期列表
        List<LocalDate> dates = new ArrayList<>();

        while(!begin.equals(end.plusDays(1))){
            dates.add(begin);
            begin = begin.plusDays(1);
        }


        //获取每日数据
        List<BusinessDataVO> dayBusinessDatas = new ArrayList<>();

        for (LocalDate date : dates) {

            LocalDateTime dayBeginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime dayEndTime = LocalDateTime.of(date,LocalTime.MAX);

            dayBusinessDatas.add(workspaceService.getBusinessData(dayBeginTime, dayEndTime));
        }


        //使用POI将数据写入excel文件

        FileInputStream inputStream = new FileInputStream(new File("D:\\app\\idea\\ideaprojects\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));

        XSSFWorkbook excel = new XSSFWorkbook(inputStream);

        XSSFSheet sheet = excel.getSheetAt(0);

        sheet.getRow(1).getCell(1).setCellValue("时间:"+begin1+"至"+end);

        //写入总览数据
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(totalBusinessData.getTurnover());
        row.getCell(4).setCellValue(totalBusinessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(totalBusinessData.getNewUsers());
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(totalBusinessData.getValidOrderCount());
        row.getCell(4).setCellValue(totalBusinessData.getUnitPrice());

        //写入明细数据
        for (int i = 0; i < dates.size(); i++) {

            BusinessDataVO dayBusinessData = dayBusinessDatas.get(i);

            row = sheet.createRow(i+7);
            row.createCell(1).setCellValue(dates.get(i).toString());
            row.createCell(2).setCellValue(dayBusinessData.getTurnover());
            row.createCell(3).setCellValue(dayBusinessData.getValidOrderCount());
            row.createCell(4).setCellValue(dayBusinessData.getOrderCompletionRate());
            row.createCell(5).setCellValue(dayBusinessData.getUnitPrice());
            row.createCell(6).setCellValue(dayBusinessData.getNewUsers());

        }

        //获取输出流将excel文件下载到客户端浏览器
        OutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

        //关闭资源
        inputStream.close();
        excel.close();
        outputStream.close();

    }
}
